package org.zheng.shop.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.zheng.shop.dto.MessageResponse;
import org.zheng.shop.entity.Company;
import org.zheng.shop.service.CompanyService;
import org.zheng.shop.service.FileStorageService;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/company")
public class CompanyController {
    
    @Autowired
    private CompanyService companyService;
    
    @Autowired
    private FileStorageService fileStorageService;
    
    @GetMapping("/info")
    public ResponseEntity<Company> getCompanyInfo() {
        Company company = companyService.getCompanyInfo();
        return ResponseEntity.ok(company);
    }
    
    @PutMapping("/update")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateCompanyInfo(@RequestBody Company company) {
        try {
            Company updatedCompany = companyService.updateCompanyInfo(company);
            return ResponseEntity.ok(updatedCompany);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new MessageResponse(e.getMessage()));
        }
    }
    
    @PostMapping("/upload/icon")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> uploadCompanyIcon(@RequestParam("file") MultipartFile file) {
        try {
            String fileName = fileStorageService.storeFile(file);
            Company company = companyService.getCompanyInfo();
            company.setIcon(fileName);
            companyService.updateCompanyInfo(company);
            return ResponseEntity.ok(new MessageResponse("文件上传成功: " + fileName));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new MessageResponse("文件上传失败: " + e.getMessage()));
        }
    }
    
    @PostMapping("/upload/qrcode")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> uploadQrcode(@RequestParam("file") MultipartFile file, @RequestParam("type") int type) {
        try {
            String fileName = fileStorageService.storeFile(file);
            Company company = companyService.getCompanyInfo();
            
            if (type == 1) {
                company.setFirstQrcode(fileName);
            } else {
                company.setSecondQrcode(fileName);
            }
            
            companyService.updateCompanyInfo(company);
            return ResponseEntity.ok(new MessageResponse("二维码上传成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new MessageResponse("二维码上传失败: " + e.getMessage()));
        }
    }
} 